import json
from datetime import datetime, timedelta
import os

data_file = '健康提醒器.json'

def load_date():
    if os.path.exists(data_file):
        with open(data_file, 'r')as f:
            return json.load(f)
    else:
        return {"record":[], "cycle_length":28}
    
def save_date(data):
    with open(data_file, 'w')as f:
        json.dump(data, f, indent=2)

def get_next_peroid(last_start, cycle_length):
    last_date = datetime.strptime(last_start, '%Y-%m-%d')
    next_date = last_date + timedelta(days=cycle_length)
    return next_date.strftime('%Y-%m-%d')

def  get_health_tips(phase):
    tips = {
        "经期": [
            "🌺 注意腹部保暖，可以使用暖宝宝",
            "💧 保持充足水分摄入",
            "🍖 多吃富含铁质的食物（红肉、菠菜等）",
            "🚫 避免剧烈运动和重体力劳动"
        ],
        "排卵期": [
            "🍵 减少咖啡因和盐分摄入",
            "💤 保证充足睡眠",
            "🧘 尝试瑜伽或冥想缓解压力",
            "🥛 增加钙质摄入"
        ],
        "经前期": [
            "🥗 注意营养均衡",
            "🏊 适合适度运动",
            "🚰 每日饮水量保持1.5-2L",
            "🔆 注意个人卫生"
        ],
        "常规期": [
            "🏃‍♀️ 保持规律运动",
            "🥦 均衡饮食补充维生素",
            "📅 记录身体变化观察规律",
            "😊 保持心情愉悦"
        ]
    }
    return tips.get(phase, tips["常规期"])

def main():
    date = load_date()

    while True:
        print("\n===== 姨妈期健康助手 =====")
        print("1. 记录新周期")
        print("2. 查看预测和提醒")
        print("3. 查看健康建议")
        print("4. 退出")
        
        choice = input('请输入你的选项:')

        if choice == '1':
            last_start = input('请输入上一次月经开始时间，格式为(YYYY-MM-DD):')
            try:
                datetime.strptime(last_start, '%Y-%m-%d')
                date['record'].append(last_start)
                date['cycle_length'] = int(input('请输入你的月经周期长度（天）')or 28)
                save_date(date)
                print('记录成功')

            except ValueError:
                print('日期格式错误，请重新输入')
                continue

        elif choice == '2':
            if not date['record']:
                print('请先记录上一次月经开始时间')
                continue

            last_start = date['record'][-1]
            next_start = get_next_peroid(last_start, date['cycle_length'])
            print(f'下一次月经开始时间预测为{next_start}')
            today = datetime.now().date()
            # next_start_date = datetime.strptime(next_start, '%Y-%m-%d').date()
            day_until = (datetime.strptime(next_start, '%Y-%m-%d').date() - today).days
            print(day_until)
            
            
            if day_until <= 3 and day_until >= 0 :
                print('距离下一次月经开始时间不足3天，请注意休息和保暖')
            
              
           
        elif choice == '3':
            if not date['record']:
                print('请先记录上一次月经开始时间')
                continue
            last_start = datetime.strptime(date['record'][-1], '%Y-%m-%d').date()
            today = datetime.now().date()
            day_since = (today - last_start).days
            phase = '常规期'
            if 0 <= day_since <= 7:
                phase = '经期'
            elif 7 < day_since <= 14:
                phase = '排卵期'
            elif 14 < day_since <= 21:
                phase = '经前期'

            print(f'当前处于{phase}，健康建议如下：')
            for tip in get_health_tips(phase):
                print(f'.{tip}')
        
        elif choice =='4':
            print('退出程序')
            break
        else:
            print('无效选项，请重新输入')

if __name__ == '__main__':
    main()




            
            

